package com.miplus.ccrm.admin.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.miplus.ccrm.common.JPubUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtToken {
    public static String build(String secret,int expiration,String usrid)
    {
        Date issDate = new Date();
        long lk=expiration;
        lk=lk*1000;
        Date expireDate = new Date(issDate.getTime()+lk);

        log.info("expireDate={},issTime={},expiration={},lk={}",
                JPubUtils.DateToString(expireDate),issDate.getTime(),expiration,lk
        );

        Map<String,Object> headerClaims = new HashMap<>();
        headerClaims.put("alg","HS256");
        headerClaims.put("typ","JWT"); //这里不是type
        return JWT.create().withHeader(headerClaims)
                .withIssuer("mi.ccrm") // 设置签发人
                .withIssuedAt(issDate) // 设置签发时间
                .withExpiresAt(expireDate) // 设置过期时间
                .withClaim("aud",usrid)
                .sign(Algorithm.HMAC256(secret));
    }

    //未来可以通过token里面的aud跟reqip来验证消息源
    public static boolean verify(String secret,String token)
    {
        if(JPubUtils.IsEmpty(secret)){
            log.warn("token verifyfail:secret null");
            return false;
        }
        try {
            JWTVerifier jwt = JWT.require(Algorithm.HMAC256(secret)).build();
            jwt.verify(token);
            log.debug("token verifyOk:{} ",token);
            return true;
        }
        catch (JWTVerificationException e){
            log.warn("token verifyfail:",e);
            return false;
        }
    }

    public static String getUser(String secret,String token)
    {
        if(JPubUtils.IsEmpty(secret)){
            log.warn("token getUser fail: secret null",token);
            return "";
        }
        try {
            JWTVerifier jwt = JWT.require(Algorithm.HMAC256(secret)).build();
            DecodedJWT decodedJwt = jwt.verify(token);
            String usrid=decodedJwt.getClaim("aud").asString();
            log.debug("token Ok getUser={}:{}",usrid,token);
            return usrid;
        }
        catch (JWTVerificationException e){
            if (e instanceof TokenExpiredException){
                log.warn("token.Expired:{}", token);
            } else{
                log.warn("token.Verifyfail:{}", token);
            }
            return "";
        }
    }

    public static String getUser(String token)
    {
        return getUser(JPubUtils.jwt_Secret,token);
    }
}
